function NIfTIPath = CreateNIfTI(pathIn, medconPath)
% 31/03/2010
% Author : Ernest Galbrun
% This function opens the input DICOM file and creates a .nii (NIfTI
% format) in the same folder named : AAA_BB_YYYYMMDD_HHhMM_aa.nii
% where AAA are the first 3 letters of the name of the patient, BB the 
% first 2 letters of its first name, YYYYMMDD_HHhMM the time and
% date of the exam and aa the age of the patient at the time of the exam
% Returns the path of the NIfTI file created
%==========================================================================

    info=dicominfo(pathIn);
    [pathstr, name, ext, versn] = fileparts(pathIn);
    
    familyName=info.PatientName.FamilyName;
    firstName=info.PatientName.GivenName;
    age=sscanf(info.PatientAge, '%dY');
    birthDate=info.PatientBirthDate;
    acquisitionDate=info.AcquisitionDate;
    sex=info.PatientSex;
    studyTime=strcat(info.StudyTime(1:2),'h',info.StudyTime(3:4));

    %replace '.' and ' ' with '_'
    familyName = regexprep(familyName, '[ .]', '_');
    familyName = fixedLength(familyName, 3, '_');
    firstName = regexprep(firstName, '[ .]', '_');
    firstName = fixedLength(firstName, 2, '_');

    % name of the new folder where NIfTI files are created :
    destFolder = fullfile(pathstr,strcat(familyName, '_', firstName));
    if ~exist(destFolder, 'dir')
        mkdir(destFolder); % creating destination folder
    end
    % Building name for the new NIfTI file:
    newNIfTI=strcat(familyName,'_', firstName, '_', acquisitionDate, '_', ...
        studyTime, '_', num2str(age));
    % Creating full path for the new NIfTI :
    NIfTIPath = fullfile(destFolder, [newNIfTI '.nii']);


    % saving DICOM header in the destination folder
    save(fullfile(destFolder,['header' newNIfTI '.mat']),'info');
    str = ['"' medconPath '" -w -rs -fv -fh -f "' ...
        pathIn '" -o "' NIfTIPath '" -c nifti'];

    system(['"' medconPath '" -w -rs -fv -fh -f "' ...
        pathIn '" -o "' NIfTIPath '" -c nifti']);
end

%==========================================================================
% UTILITY FUNCTIONS
%==========================================================================

% fixed length takes the first N letters of input strings. If the string
% contains less thant N characters, fills with char fillingChar
function strOut = fixedLength(str, N, fillingChar)
    str = upper(str);
    if length(str) > N
        str = str(1:N);
    else
        while length(str) < N
            str = strcat(str,fillingChar);
        end
    end
    strOut = str;
end